package com.mmc.tianmu.im.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.mmc.tianmu.im.entity.ChatMessage;
import com.mmc.tianmu.im.service.ChatService;

/**
 * @author 作者 geDuo
 * @version 创建时间：2021年8月6日 下午4:38:49
 * @explain Redis订阅频道处理类
 */
@Component
public class RedisListenerHandle extends MessageListenerAdapter {
	private static final Logger LOGGER = LoggerFactory.getLogger(RedisListenerHandle.class);

	@Value("${redis.channel.msgToAll}")
	private String msgToAll;

	@Value("${server.port}")
	private String serverPort;

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Autowired
	private ChatService chatService;

	/**
	 * 收到监听消息
	 * 
	 * @param message
	 * @param bytes
	 */
	@Override
	public void onMessage(Message message, byte[] bytes) {
		byte[] body = message.getBody();
		byte[] channel = message.getChannel();
		String rawMsg;
		String topic;
		try {
			rawMsg = redisTemplate.getStringSerializer().deserialize(body);
			topic = redisTemplate.getStringSerializer().deserialize(channel);
			LOGGER.info("Received raw message from topic:" + topic + ", raw message content：" + rawMsg);
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
			return;
		}

		if (msgToAll.equals(topic)) {
			LOGGER.info("Send message to all users:" + rawMsg);
			ChatMessage chatMessage = JsonUtil.parseJsonToObj(rawMsg, ChatMessage.class);
			// 发送消息给所有在线Cid
			chatService.sendMsg(chatMessage);
		} else {
			LOGGER.warn("No further operation with this topic!");
		}
	}

}
